<template>
	<div id="send-message-wrapper" class="shadow">
		<Spin fix v-show="spinShow"></Spin>
		<div class="top-title">用户发送消息给公众号</div>
		<div class="disFlex">
			<div class="reply-miniprogram Flex">
				<Form ref="replyMiniprogram" :label-width="120" :model='replyMiniprogram' :rules='replyMiniprogramRule' label-position="left">
					<FormItem label="关键字内容" prop="receive_keyword">
						<Input style="width: 50%;" v-model="replyMiniprogram.receive_keyword" placeholder="关键字内容"></Input>
					</FormItem>
					<FormItem label="自动回复类型" prop="reply_type">
						<RadioGroup v-model="reply_type" @on-change="chaneType">
							<Radio label="miniprogram">
								<span>回复小程序卡片</span>
							</Radio>
							<Radio label="text">
								<span>回复文本信息</span>
							</Radio>
						</RadioGroup>
					</FormItem>

					<!-- 纯文本回复formitem -->
					<template v-if="reply_type == 'text'">
						<FormItem label="自动回复内容" prop="text_content">
							<div class="flex column start">
								<div style="margin-bottom: 15px;">
									<Button type="primary" @click="showAddMiniprogramLink=true">添加小程序链接</Button>
								</div>
								<Input id="replyText" type="textarea" style="width: 50%;" :rows="10" v-model="replyMiniprogram.text_content" placeholder="自动回复内容"></Input>
								<p style="color: gray;">文案内容如果包含粉丝昵称，请用 <span style="color:red;">{nickname}</span> 代替</p>
								<p style="color: gray;">{{replyMiniprogram.notify}}</p>
							</div>	
						</FormItem>
					</template>	

					<!-- 小程序卡片回复formitem -->
					<template v-else>
						<FormItem label="小程序卡片路径" prop="miniprogram_page_path">
							<div class="flex center">
								<Select v-model="replyMiniprogram.miniprogram_page_path_opt"  @on-change="chageSel()" class="select-wrapper">
									<Option :value=0>首页</Option>
									<Option :value=1>微页面</Option>
									<Option :value=2>商品</Option>
									<Option :value=3>企业</Option>
								</Select>
								<Input style="width: 300px;" readonly v-model="replyMiniprogram.miniprogram_page_path" @click.native="tapInput" placeholder="请选择卡片路径"></Input>
							</div>
						</FormItem>
						<FormItem label="小程序卡片标题" prop="miniprogram_title">
							<Input style="width: 300px;" v-model="replyMiniprogram.miniprogram_title" placeholder="小程序卡片标题"></Input>
						</FormItem>
						<FormItem label="小程序卡片图片" prop="miniprogram_page_thumb_url">
							<div class="upload-operate-wrapper">
								<Button type="primary" ghost class="upload-img-btn">
									上传图片
									<input type="file" accept="image/gif, image/jpeg, image/png, image/jpg" @change="handleFileChange"></input>
								</Button>
								<span>推荐尺寸:1280*840格式</span>
							</div>
							<img  class="upload-img" style="width: 120px; height: 92px;" v-if="replyMiniprogram.miniprogram_page_thumb_url!=''" :src="replyMiniprogram.miniprogram_page_thumb_url"/>
						</FormItem>

					</template>	
					
					
				</Form>
				<Button type="primary" @click="handleSubmit('replyMiniprogram')" style="margin-left: 120px;">
						保存
				</Button>
			</div>
			<div class="disFlex vertical">
				<div v-if="reply_type == 'text'">
					<p class="demo-title">消息预览</p>
					<div class="preview-wrapper disFlex">
						<img :src="replyMiniprogram.logo" alt="">
						<p v-html="reply_text_html"></p>
					</div>	
				</div>
				<p class="demo-title">示意</p>
				<img :class="reply_type == 'text'?'img-demo-reply-text':'img-demo-reply-miniprogram'" :src="reply_type == 'text'?replyMiniprogram.remind_image_text:replyMiniprogram.remind_image_miniprogram" alt=""/>
			</div>
		</div>
		
		
		<Modal v-model="showAddMiniprogramLink">
	        <p slot="header" style="color:rgb(8, 93, 196);text-align:center">
	            <span>添加小程序链接</span>
	        </p>
	        <div class="model-miniprogram-wrapper">
		        <Form ref="modelMiniprogram" :label-width="120" :model='modelMiniprogram' :rules='modelMiniprogramRule' label-position="left">
					<FormItem label="小程序卡片路径" prop="miniprogram_path">
						<div class="flex center">
							<Select v-model="modelMiniprogram.miniprogram_type"  @on-change="choseMiniprogramType()" class="select-wrapper">
								<Option :value=0>首页</Option>
								<Option :value=1>微页面</Option>
								<Option :value=2>商品</Option>
								<Option :value=3>企业</Option>
							</Select>
							<Input style="width: 250px;" readonly v-model="modelMiniprogram.miniprogram_path" @click.native="tapModelInput" placeholder="请选择跳转路径"></Input>
						</div>
					</FormItem>
					<FormItem label="链接文案" prop="link_title">
						<Input style="width: 300px;" v-model="modelMiniprogram.link_title" placeholder="小程序卡片标题"></Input>
					</FormItem>
				</Form>
	        </div>
	        <div slot="footer">
	            <div class="flex center column-center">
					<Button @click="showAddMiniprogramLink=false">取消</Button>
	            	<Button type="primary" @click="saveModal">保存</Button>
				</div>
	        </div>
	    </Modal>

		<!-- 商品选择器 -->
		<goodsSelect buyMode="-9" @confirm="commitGoodsFn" :selectNum="1" ref="goodsModal"></goodsSelect>
		<!-- 微页面选择器 -->
		<micropage-select ref="micropageModal" @confirm="chosePages"></micropage-select>
		<!-- 企业选择器 -->
   	    <shop-select ref="shopselect" @commitShopFn="commitShopFn"></shop-select>
   
	</div>
</template>

<script>
	import { uploadImage } from 'api/uploadImage'
	import { getKeywordReplyDetail,keywordReplyUpdate,keywordReplyCreate } from "api/wechatSetting"

	import { getCache } from 'common/js/util'

	// 商品选择器组件
	import goodsSelect from 'base/goods-select/goods-select'
	// 企业选择器
	import shopSelect from 'base/shopSelect/shopSelect'
	// 微页面选择器组件
	import MicropageSelect from 'base/micropage-select/micropage-select'

	export default {
        data () {
            return {
				spinShow: false,
				showAddMiniprogramLink: false,
				reply_type: "miniprogram",
				// 回复表单
				replyMiniprogram: {
					// 关键词
					receive_keyword: "",
					// 回复类型 text文本信息 miniprogram 小程序卡片
					reply_type: "miniprogram", 
					// 小程序卡片路径类型
					miniprogram_page_path_opt: 0,
					// 小程序卡片路径
					miniprogram_page_path: "app/mallA/index/index",
					// 小程序卡片标题
					miniprogram_title: "",
					// 小程序卡片图片
					miniprogram_page_thumb_url: "",
					// 回复文本内容
					text_content: ""
				},
				miniprogramRule: {
					receive_keyword: [{ required: true, message: '关键词不能为空', trigger: 'blur' }],
					reply_type: [{ required: true, message: '自动回复信息类型不能为空', trigger: 'blur' }],
					miniprogram_page_path: [{ required: true, message: '小程序卡片路径不能为空', trigger: 'blur' }],
					miniprogram_title: [{ required: true, message: '小程序卡片标题不能为空', trigger: 'blur' }],
					miniprogram_page_thumb_url: [{ required: true, message: '小程序卡片图片不能为空', trigger: 'blur' }]
				},
				textRule: {
					receive_keyword: [{ required: true, message: '关键词不能为空', trigger: 'blur' }],
					reply_type: [{ required: true, message: '自动回复信息类型不能为空', trigger: 'blur' }],
					text_content: [{ required: true, message: '回复内容不能为空', trigger: 'blur' }],
				},
				
				// 添加小程序链接表单
				modelMiniprogram: {
					// 路径类型
					miniprogram_type: 0,
					// 跳转路径
					miniprogram_path: "app/mallA/index/index",
					// 链接文案
					link_title: ""
				},

				// 添加小程序链接表单规则
				modelMiniprogramRule: {
					miniprogram_path: [{ required: true, message: '小程序链接不能为空', trigger: 'change' }],
					link_title: [{ required: true, message: '小程序链接文案不能为空', trigger: 'blur' }]
				}

			}
        },
        methods: {
			chaneType() {
				var tmp = JSON.parse(JSON.stringify(this.replyMiniprogram));
				this.$refs.replyMiniprogram.resetFields();
				this.replyMiniprogram = tmp;
				// this.$refs[name].resetFields();
			},
			
			handleSubmit (name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
						this.replyMiniprogram.reply_type = this.reply_type;
						if (this.replyId == -1) {
							// 新建关键字
							keywordReplyCreate(this.replyMiniprogram).then(_res=>{
								this.$Message.success("创建成功");
								this.$router.push("/mall/wechatSetting/sendMessage");	
							}).catch(err=>{
								this.$Message.error(err.message);
							})
						} else {
							// 更新关键字
							keywordReplyUpdate(this.replyMiniprogram).then(_res=>{
								this.$Message.success("更新成功")
							}).catch(err=>{
								this.$Message.error(err.message);
							})
						}
						
                    } else {
                        this.$Message.error('请填写完整信息!');
                    }
                })
            },
			handleFileChange (event) {
				var that = this;
				this.spinShow = true;
				uploadImage(event.target.files[0]).then(imgUrl => {
					that.spinShow = false;
					that.replyMiniprogram.miniprogram_page_thumb_url = imgUrl;
				}).catch(err => {
					that.spinShow = false;
					that.$Message.error(err);  
				})  
			},
			
			// 卡片路径类型切换
			chageSel() {
				if (this.replyMiniprogram.miniprogram_page_path_opt == 0) {
					this.replyMiniprogram.miniprogram_page_path = "app/mallA/index/index";
				} else {
					this.replyMiniprogram.miniprogram_page_path = "";
				}
			},

			// 小程序链接卡片路径类型切换
			choseMiniprogramType() {
				if (this.modelMiniprogram.miniprogram_type == 0) {
					this.modelMiniprogram.miniprogram_path = "app/mallA/index/index";
				} else {
					this.modelMiniprogram.miniprogram_path = "";
				}
			},
			tapInput() {
				this.choseType = 0;
				if (this.replyMiniprogram.miniprogram_page_path_opt == 1) { 
					// 微页面
					this.$refs.micropageModal.show();
				} else if (this.replyMiniprogram.miniprogram_page_path_opt == 2) { 
					// 商品
					this.$refs.goodsModal.show()
				} else if (this.replyMiniprogram.miniprogram_page_path_opt == 3) { 
					// 企业
					this.$refs.shopselect.openFn("");
				}
			},
			tapModelInput() {
				this.choseType = 1;
				if (this.modelMiniprogram.miniprogram_type == 1) { 
					// 微页面
					this.$refs.micropageModal.show();
				} else if (this.modelMiniprogram.miniprogram_type == 2) { 
					// 商品
					this.$refs.goodsModal.show()
				} else if (this.modelMiniprogram.miniprogram_type == 3) { 
					// 企业
					this.$refs.shopselect.openFn("");
				}
			},
			getData() {
				this.spinShow = true;
				getKeywordReplyDetail({plugin_custom_reply_id: this.replyId}).then(_res=>{
					this.spinShow = false;
					this.replyMiniprogram = _res.data;
					this.reply_type = _res.data.reply_type;
				}).catch(err=>{
					this.spinShow = false;
					this.$Message.error(err.message);
				})
			},

			// 选中商品回调
			commitGoodsFn(_id){
				if (this.choseType == 0) {
					// 回复小程序卡片选择
					if (_id != "") {
						this.replyMiniprogram.miniprogram_page_path = "app/mall/item/item?goodsId="+_id;
					} else {
						this.replyMiniprogram.miniprogram_page_path = "";
					}
				} else {
					// 弹窗选择
					if (_id != "") {
						this.modelMiniprogram.miniprogram_path = "app/mall/item/item?goodsId="+_id;
					} else {
						this.modelMiniprogram.miniprogram_path = "";
					}
				}
			},

			// 选中微页面回调
			chosePages(ids) {
				if (this.choseType == 0) {
					// 回复小程序卡片选择
					if (ids.length>0) {
						this.replyMiniprogram.miniprogram_page_path = "app/mall/label/label?labelId="+ids[0];
					} else {
						this.replyMiniprogram.miniprogram_page_path = "";
					}
				} else {
					// 弹窗选择
					if (ids.length>0) {
						this.modelMiniprogram.miniprogram_path = "app/mall/label/label?labelId="+ids[0];
					} else {
						this.modelMiniprogram.miniprogram_path = "";
					}
				}
			},

			 // 企业选中回调
			commitShopFn(arr){
				if (this.choseType == 0) {
					// 回复小程序卡片选择
					if (arr.length > 0) {
						this.replyMiniprogram.miniprogram_page_path = "app/shop/index/index?shopId=" + arr[0].shop_id;
					} else {
						this.replyMiniprogram.miniprogram_page_path = "";
					}
				} else {
					// 弹窗选择
					if (arr.length > 0) {
						this.modelMiniprogram.miniprogram_path = "app/shop/index/index?shopId=" + arr[0].shop_id;
					} else {
						this.modelMiniprogram.miniprogram_path = "";
					}
				}
				
			},

			// 保存弹框添加小程序链接内容
			saveModal() {
				this.$refs.modelMiniprogram.validate((valid) => {
                    if (valid) {
						this.showAddMiniprogramLink = false;
						var title = `<a data-miniprogram-appid="${this.wechatAppid}" data-miniprogram-path="${this.modelMiniprogram.miniprogram_path}"  href="http://">${this.modelMiniprogram.link_title}</a>`;
						this.addCursor(document.getElementById("replyText").children[0], title);
                    } else {
                        this.$Message.error('请填写完整信息!');
                    }
                })
			},

			// 获取光标位置
		    getCursor(textarea) {
				var rangeData = {text: "", start: 0, end: 0 };
				if (textarea.setSelectionRange) { // W3C	
					textarea.focus();
					rangeData.start= textarea.selectionStart;
					rangeData.end = textarea.selectionEnd;
					rangeData.text = (rangeData.start != rangeData.end) ? textarea.value.substring(rangeData.start, rangeData.end): "";
				} else if (document.selection) { // IE
					textarea.focus();
					var i,
						oS = document.selection.createRange(),
						// Don't: oR = textarea.createTextRange()
						oR = document.body.createTextRange();
					oR.moveToElementText(textarea);
					
					rangeData.text = oS.text;
					rangeData.bookmark = oS.getBookmark();
					
					// object.moveStart(sUnit [, iCount]) 
					// Return Value: Integer that returns the number of units moved.
					for (i = 0; oR.compareEndPoints('StartToStart', oS) < 0 && oS.moveStart("character", -1) !== 0; i ++) {
						// Why? You can alert(textarea.value.length)
						if (textarea.value.charAt(i) == '\r' ) {
							i ++;
						}
					}
					rangeData.start = i;
					rangeData.end = rangeData.text.length + rangeData.start;
				}
				return rangeData;
			},
			// 设置光标位置
			setCursor(textarea, rangeData) {
				var oR, start, end;
				textarea.focus();
				if (textarea.setSelectionRange) { // W3C
					textarea.setSelectionRange(rangeData.start, rangeData.end);
				} else if (textarea.createTextRange) { // IE
					oR = textarea.createTextRange();
					// Fixbug : ues moveToBookmark()
					// In IE, if cursor position at the end of textarea, the set function don't work
					if(textarea.value.length === rangeData.start) {
						//alert('hello')
						oR.collapse(false);
						oR.select();
					} else {
						oR.moveToBookmark(rangeData.bookmark);
						oR.select();
					}
				}
			},
			// 添加文字
			addCursor(textarea, text) {
				var oValue, nValue, oR, sR, nStart, nEnd, st;
				var rangeData = this.getCursor(textarea);
				this.setCursor(textarea, rangeData);

				if (textarea.setSelectionRange) { // W3C
					oValue = textarea.value;
					nValue = oValue.substring(0, rangeData.start) + text + oValue.substring(rangeData.end);
					nStart = nEnd = rangeData.start + text.length;
					st = textarea.scrollTop;
					textarea.value = nValue;
					this.replyMiniprogram.text_content = nValue;
					// Fixbug:
					// After textarea.values = nValue, scrollTop value to 0
					if(textarea.scrollTop != st) {
						textarea.scrollTop = st;
					}
					textarea.setSelectionRange(nStart, nEnd);
				} else if (textarea.createTextRange) { // IE
					sR = document.selection.createRange();
					sR.text = text;
					this.replyMiniprogram.text_content = text;
					sR.setEndPoint('StartToEnd', sR);
					sR.select();
				}

			},

		    getCookie(c_name) {
				if (document.cookie.length>0) {
					c_start=document.cookie.indexOf(c_name + "=")
					if (c_start!=-1){ 
						c_start=c_start + c_name.length+1 
						c_end=document.cookie.indexOf(";",c_start)
						if (c_end==-1) c_end=document.cookie.length
						return unescape(document.cookie.substring(c_start,c_end))
					} 
				}
				return ""
			
			}
		},
		computed: {
			// 回复表单规则
			replyMiniprogramRule: function() {
				if (this.reply_type == "text") {
					return {
						receive_keyword: [{ required: true, message: '关键词不能为空', trigger: 'blur' }],
						reply_type: [{ required: true, message: '自动回复信息类型不能为空', trigger: 'blur' }],
						text_content: [{ required: true, message: '回复内容不能为空', trigger: 'blur' }]
					}
				} else {
					return {
						receive_keyword: [{ required: true, message: '关键词不能为空', trigger: 'blur' }],
						reply_type: [{ required: true, message: '自动回复信息类型不能为空', trigger: 'blur' }],
						miniprogram_page_path: [{ required: true, message: '小程序卡片路径不能为空', trigger: 'change' }],
						miniprogram_title: [{ required: true, message: '小程序卡片标题不能为空', trigger: 'blur' }],
						miniprogram_page_thumb_url: [{ required: true, message: '小程序卡片图片不能为空', trigger: 'blur' }]
					}
				}
			},
			top_title: function() {
				return this.subscribeType == "entranceWechat" ? "用户进入公众号" : "用户关注公众号"
			},
			reply_text_html: function() {
				// let str = this.replyMiniprogram.text_content.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(/<a data-miniprogram/g, '<img src="/static/miniprogram.png" style="width:20px;margin-right:5px;" alt=""/><a data-miniprogram');
				let str = this.replyMiniprogram.text_content.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>');
				return str;
			}
		},
        created() {
			// 获取回复id
			this.replyId = this.$route.params.id?this.$route.params.id:-1;
			this.wechatAppid = getCache("wechat_app_id");
			this.replyMiniprogram.logo = getCache("logo");
			this.replyMiniprogram.remind_image_text = getCache("remind_image_text");
			this.replyMiniprogram.remind_image_miniprogram = getCache("remind_image_miniprogram");

			if (this.replyId != -1) {
				this.getData();
			}
        },
        components: {
			goodsSelect,MicropageSelect,shopSelect
		}
     }
</script>

<style scoped>
	#send-message-wrapper {
		background: white;
		margin: 24px;
		padding: 20px;
		font-size: 14px;
		position: relative;
	}
	.top-title {
		background: #f5f7f9;
		color: black;
		padding: 10px;
		font-size: 14px;
	}
	.follow-content {
		background: white;
		padding: 20px;
	}
	.follow-content img {
		width: 33.33%;
	}
	/*上传图片*/
	.upload-operate-wrapper {
		display: flex;
	}
	.upload-operate-wrapper span {
		color: darkgray;
		margin-left: 6px;
	}
	.upload-img-btn {
		position: relative;
		
	}
	.upload-img-btn input {
		position: absolute;
		opacity: 0;
		left: 0;top: 0;width: 100%;height: 100%;
	}
	.upload-img {
		width: 284px;
		margin-top: 10px;
		border: 1px solid #F2F2F2;
	}
	
	.cropper-wrapper {
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.cropper-content {
		width: 200px;
		height: 200px;
	}
	
	.reply-miniprogram {
		padding: 20px;
	}
	.select-wrapper {
		width: 128px;
		margin-right: 15px;
	}

	.upload-operate-wrapper {
		display: flex;
		align-items: center;
	}
	.upload-operate-wrapper span {
		color: darkgray;
		margin-left: 6px;
	}
	.upload-img-btn {
		position: relative;
	}
	.upload-img-btn input {
		position: absolute;
		opacity: 0;
		left: 0;top: 0;width: 100%;height: 100%;
	}
	.upload-img {
		margin-top: 10px;
		border: 1px solid #F2F2F2;
	}

	.preview-wrapper {
		width: 370px;
		min-width: 370px;
		height: 200px;
		padding: 10px;
	    background-color: rgb(233, 229, 233);
	    border: 1px solid #ddd;
	    border-radius: 4px;
	    margin-left: 20px;
	}

	.preview-wrapper img {
		width: 40px;
		min-width: 40px;
		height: 40px;
		background: gray;
		margin-right: 10px;
	}
	
	.preview-wrapper p {
		background: white;
		width: 230px;
		border-radius: 5px;
		padding: 10px;
		color: black;
		font-size: 16px;
		overflow-y: auto;
		word-wrap: break-word;
	}

	.demo-title {
		text-align: center;
		padding: 10px;
		color: black;
	}

	.img-demo-reply-text {
		display: inline-block;
	    width: 370px;
		min-width: 370px;
	    height: 270px;
	    padding: 4px;
	    background-color: #fff;
	    border: 1px solid #ddd;
	    border-radius: 4px;
	    margin-left: 20px;
	}

	.img-demo-reply-miniprogram {
		display: inline-block;
	    width: 370px;
	    min-width: 370px;
	    height: 380px;
	    padding: 4px;
	    background-color: #fff;
	    border: 1px solid #ddd;
	    border-radius: 4px;
	    margin-left: 20px;
	}
</style>

<style type="text/css">
	/* .ivu-form .ivu-form-item-label {
		font-size: 14px;
		font-weight: bold;
	} */
</style>